package top.lzy.hive.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.util.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.lzy.hive.entity.Country;
import top.lzy.hive.service.FileService;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.annotation.Resource;

@Service
public class FileServiceImpl implements FileService {
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Country> parseFile(MultipartFile file) throws IOException {
        // 解析excel
        List<Country> list = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), Country.class, new PageReadListener<Country>(list::addAll)).sheet().doRead();
        // 筛选异常值
        list.forEach(country -> {
            country.setIsError(false);
            country.setErrorFiled("-");
            country.setErrorMsg("-");
            if (Objects.isNull(country.getSystemicCrisis()) || (country.getSystemicCrisis() != 0 && country.getSystemicCrisis() != 1)) {
                country.setIsError(true);
                country.setErrorFiled("systemic_crisis");
                country.setErrorMsg("系统性危机字段值范围：【0|1】");
            }
            if (Objects.isNull(country.getDomesticDebtInDefault()) || (country.getDomesticDebtInDefault() != 0 && country.getDomesticDebtInDefault() != 1)) {
                country.setIsError(true);
                country.setErrorFiled("domestic_debt_in_default");
                country.setErrorMsg("主权内债务违约字段值范围：【0|1】");
            }
            if (Objects.isNull(country.getSovereignExternalDebtDefault()) || (country.getSovereignExternalDebtDefault() != 0 && country.getSovereignExternalDebtDefault() != 1)) {
                country.setIsError(true);
                country.setErrorFiled("sovereign_external_debt_default");
                country.setErrorMsg("主权外债务违约字段值范围：【0|1】");
            }
            if (Objects.isNull(country.getIndependence()) || (country.getIndependence() != 0 && country.getIndependence() != 1)) {
                country.setIsError(true);
                country.setErrorFiled("independence");
                country.setErrorMsg("独立性字段值范围：【0|1】");
            }
            if (Objects.isNull(country.getCurrencyCrises()) || (country.getCurrencyCrises() != 0 && country.getCurrencyCrises() != 1)) {
                country.setIsError(true);
                country.setErrorFiled("currency_crises");
                country.setErrorMsg("货币危机字段值范围：【0|1】");
            }
            if (Objects.isNull(country.getInflationCrises()) || (country.getInflationCrises() != 0 && country.getInflationCrises() != 1)) {
                country.setIsError(true);
                country.setErrorFiled("inflation_crises");
                country.setErrorMsg("通货膨胀危机字段值范围：【0|1】");
            }
            if (StringUtils.isBlank(country.getBankingCrisis()) || !"no_crisis".equals(country.getBankingCrisis()) && !"crisis".equals(country.getBankingCrisis())) {
                country.setIsError(true);
                country.setErrorFiled("banking_crisis");
                country.setErrorMsg("货币危机字段值范围：【no_crisis|crisis】");
            }
        });
        String userDir = System.getProperty("user.dir");
        String filePath = userDir + "\\src\\main\\resources\\static\\country_data.txt";
        StringBuilder sb = new StringBuilder();
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            String spiltCh = "\t";
            for (Country country : list) {
                sb.append(country.getCaseNum()).append(spiltCh)
                        .append(country.getCc3()).append(spiltCh)
                        .append(country.getCountry()).append(spiltCh)
                        .append(country.getYear()).append(spiltCh)
                        .append(country.getSystemicCrisis()).append(spiltCh)
                        .append(country.getExchUsd()).append(spiltCh)
                        .append(country.getDomesticDebtInDefault()).append(spiltCh)
                        .append(country.getSovereignExternalDebtDefault()).append(spiltCh)
                        .append(country.getGdpWeightedDefault()).append(spiltCh)
                        .append(country.getInflationAnnualCpi()).append(spiltCh)
                        .append(country.getIndependence()).append(spiltCh)
                        .append(country.getCurrencyCrises()).append(spiltCh)
                        .append(country.getInflationCrises()).append(spiltCh)
                        .append(country.getBankingCrisis()).append(spiltCh)
                        .append(country.getIsError()).append(spiltCh)
                        .append(country.getErrorFiled()).append(spiltCh)
                        .append(country.getErrorMsg());
                sb.append("\n"); // 每一行结束后添加换行符
            }
            writer.write(sb.toString());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        // 存储值信息 (已存储)
        return list;
    }

    @Override
    public List<Country> getCountries() {
        String sql = "select * from country";
        return jdbcTemplate.query(sql, (rs, rowNum) -> {
            Country country = new Country();
            country.setCaseNum(rs.getInt("case_num"));
            country.setCc3(rs.getString("cc3"));
            country.setCountry(rs.getString("country"));
            country.setYear(rs.getInt("year"));
            country.setSystemicCrisis(rs.getInt("systemic_crisis"));
            country.setExchUsd(rs.getDouble("exch_usd"));
            country.setDomesticDebtInDefault(rs.getInt("domestic_debt_in_default"));
            country.setSovereignExternalDebtDefault(rs.getInt("sovereign_external_debt_default"));
            country.setGdpWeightedDefault(rs.getDouble("gdp_weighted_default"));
            country.setInflationAnnualCpi(rs.getDouble("inflation_annual_cpi"));
            country.setIndependence(rs.getInt("independence"));
            country.setCurrencyCrises(rs.getInt("currency_crises"));
            country.setInflationCrises(rs.getInt("inflation_crises"));
            country.setBankingCrisis(rs.getString("banking_crisis"));
            country.setIsError(rs.getBoolean("is_error"));
            country.setErrorMsg(rs.getString("error_msg"));
            return country;
        });
    }
}
